import pygame
import sys

# 初始化 Pygame
pygame.init()

# 设置窗口尺寸
WIDTH, HEIGHT = 640, 480
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Bouncing Ball Game")

# 设置颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# 设置球和平台的初始位置和大小
ball_pos = [WIDTH // 2, HEIGHT // 2]
ball_radius = 15
ball_speed = [2, 2]

paddle_pos = [WIDTH // 2 - 60 // 2, HEIGHT - 30]
paddle_width, paddle_height = 60, 10

# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 移动平台
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and paddle_pos[0] > 0:
        paddle_pos[0] -= 5
    if keys[pygame.K_RIGHT] and paddle_pos[0] < WIDTH - paddle_width:
        paddle_pos[0] += 5

    # 移动球
    ball_pos[0] += ball_speed[0]
    ball_pos[1] += ball_speed[1]

    # 球碰到墙壁反弹
    if ball_pos[0] <= 0 or ball_pos[0] >= WIDTH:
        ball_speed[0] = -ball_speed[0]
    if ball_pos[1] <= 0:
        ball_speed[1] = -ball_speed[1]
    if ball_pos[1] >= HEIGHT:
        running = False  # 球落到底部，游戏结束

    # 球和平台碰撞
    if (paddle_pos[0] < ball_pos[0] < paddle_pos[0] + paddle_width) and (paddle_pos[1] < ball_pos[1] < paddle_pos[1] + paddle_height):
        ball_speed[1] = -ball_speed[1]

    # 填充背景色
    screen.fill(WHITE)

    # 绘制球和平台
    pygame.draw.circle(screen, RED, ball_pos, ball_radius)
    pygame.draw.rect(screen, RED, (paddle_pos[0], paddle_pos[1], paddle_width, paddle_height))

    # 更新屏幕显示
    pygame.display.flip()

    # 控制游戏循环的帧率
    pygame.time.Clock().tick(60)

pygame.quit()
sys.exit()